xquery version "1.0";

module namespace partintmod="http://www.example.com/partintmod";

declare namespace dc = "http://purl.org/dc/elements/1.1/";
declare namespace pm = "http://www.politicalmashup.nl";
declare namespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

import module namespace addf="http://www.example.com/addf" at "xmldb:exist:///db/projdb/modules/addf.xqm";
import module namespace activity="http://www.example.com/activity" at "xmldb:exist:///db/projdb/modules/activity.xqm";

declare function partintmod:list_of_initiators_and_participants_per_topic($topics, $list_of_speakers) {
    (:foreach topic:)
    <topics>
    {
        for $topic in $topics
            let $topic-title := data($topic/@pm:title)
            let $initiators := 
                for $speaker in $list_of_speakers
                    where contains(addf:substring-before-if-contains($topic-title, ' tot '), $speaker)
                    return <initiator>{$speaker}</initiator>
            let $participants-list := for $p in $topic/pm:speech
                where data($p/@pm:role) != 'chair'
                return data($p/@pm:speaker)
            let $participants := for $participant in distinct-values($participants-list)
                return <participant>{$participant}</participant>
            return <topic id="{$topic/@pm:id}" date="{data($topic/parent::*/parent::*/meta/dc:date)}">
                   <title>{$topic-title}</title>
                   <participants>{$participants}</participants>
                   <initiators>{$initiators}</initiators>
                   </topic>
    }
    </topics>
};
(:
let $periods := ('2009-2010') (:, '2010-2011', '2011-2012', '2012-2013', '2013-2014':)
let $speaker_file := doc('/db/projdb/lijst_van_sprekers_ge2009.xml')
let $mayors_file := doc('/db/projdb/lijst_burgemeesters_2007.xml')
let $output_collection := 'xmldb:exist:///db/projdb'
let $iandp_file := doc('/db/projdb/initiators_and_participants_ge2009.xml'):)
declare function partintmod:create_initiators_and_participants($doc, $speaker_file, $output_collection, $output_file ) {

(: list of speakers :)
let $list_of_speakers := distinct-values(data($speaker_file/speakers/speaker/name))

(: list of all topics of interest :)
let $topics := $doc/root/pm:proceedings/pm:topic[data(@pm:title) != "MOTIE VAN ORDE"]

(: store result in db :)
(:let $output_file := 'initiators_and_participants_ge2009.xml':)
let $store-return-status := xmldb:store(
    $output_collection, 
    $output_file, 
    partintmod:list_of_initiators_and_participants_per_topic($topics, $list_of_speakers))

return <message>New Document Created {$store-return-status} at {$output_collection }/{$output_file}</message>
};